package com.htudata.zabbix.trigger.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;

import com.htudata.core.util.operation.ArrayOperationUtils;
import com.htudata.core.util.operation.CollectionsOperationUtils;
import com.htudata.core.util.operation.StringOperationUtils;
import com.htudata.zabbix.api.service.TriggerZabbixApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ZBXTriggerService {

  public static final String PRE_EXPRESSION_FORMAT = "<server>:<key>.<function>(<parameter>)";
  
  public static final String EXPRESSION_FORMAT = "{<server>:<key>.<function>(<parameter>)}<operator><constant>";
  
  @Autowired
  private TriggerZabbixApiService triggerZabbixApiService;
  
  public static boolean isValidZBXTriggerId(String id) {
    if (StringOperationUtils.isPositiveInt(id))
      return true; 
    return false;
  }
  
  public static String resolveExpression(String expression, JSONArray functions, JSONArray items, JSONArray hosts) {
    String result = expression;
    for (Map.Entry<String, Object> entry : (Iterable<Map.Entry<String, Object>>)getExtendFunctions(functions, items, hosts).entrySet())
      result = result.replace(entry.getKey(), getPreExpression((JSONObject)entry.getValue())); 
    return result;
  }
  
  public static JSONObject getExtendFunctions(JSONArray functions, JSONArray items, JSONArray hosts) {
    JSONObject result = new JSONObject();
    for (Object obj : functions) {
      JSONObject function = (JSONObject)obj;
      for (Object obj2 : items) {
        JSONObject item = (JSONObject)obj2;
        if (!function.getString("itemid").equals(item.getString("itemid")))
          continue; 
        for (Object obj3 : hosts) {
          JSONObject host = (JSONObject)obj3;
          if (!item.getString("hostid").equals(host.getString("hostid")))
            continue; 
          function.putAll((Map)item);
          function.putAll((Map)host);
          result.put(function.getString("functionid"), function);
        } 
      } 
    } 
    return result;
  }
  
  public static String getPreExpression(JSONObject extendFunction) {
    String result = "<server>:<key>.<function>(<parameter>)";
    result = result.replace("<server>", extendFunction.getString("host"));
    result = result.replace("<key>", extendFunction.getString("key_"));
    result = result.replace("<function>", extendFunction.getString("function"));
    result = result.replace("<parameter>", extendFunction.getString("parameter"));
    return result;
  }
  
  public JSONArray getZBXTriggers(String[] groupIdArr, String[] hostIdArr, String[] templateIdArr, int limit) throws Exception {
    JSONObject params = new JSONObject();
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("sortfield", "triggerid");
    params.put("sortorder", "DESC");
    params.put("output", new String[] { "triggerid", "description", "expression", "priority", "value", "status", "error" });
    if (ArrayOperationUtils.isValidArr((Object[])groupIdArr))
      params.put("groupids", groupIdArr); 
    if (ArrayOperationUtils.isValidArr((Object[])hostIdArr))
      params.put("hostids", hostIdArr); 
    if (ArrayOperationUtils.isValidArr((Object[])templateIdArr))
      params.put("templateids", templateIdArr); 
    params.put("selectHosts", new String[] { "hostid", "host" });
    params.put("selectItems", new String[] { "itemid", "key_", "hostid" });
    params.put("selectFunctions", new String[] { "functionid", "name", "parameter", "itemid" });
    String json = this.triggerZabbixApiService.getTriggers(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    JSONArray result = root.getJSONArray("result");
    return result;
  }
  
  public JSONArray getZBXTriggerInfo(Long[] itemIdArr, int limit)  throws Exception {
    JSONObject params = new JSONObject();
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("sortfield", "triggerid");
    params.put("sortorder", "DESC");
    params.put("output", new String[] { "triggerid", "description", "comments", "expression", "priority", "status", "manual_close" });
    if (ArrayOperationUtils.isValidArr((Object[])itemIdArr))
      params.put("triggerids", itemIdArr); 
    params.put("selectHosts", new String[] { "hostid", "host" });
    params.put("selectItems", new String[] { "itemid", "key_", "hostid" });
    params.put("selectFunctions", new String[] { "functionid", "name", "parameter", "itemid" });
    String json = this.triggerZabbixApiService.getTriggers(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    JSONArray result = root.getJSONArray("result");
    return result;
  }
  
  public <T> JSONObject getZBXTriggerIdsAndItemId(List<T> triggerIdList, int limit)  throws Exception {
    JSONObject params = new JSONObject();
    params.put("preservekeys", Boolean.valueOf(true));
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("output", new String[] { "triggerid" });
    if (CollectionsOperationUtils.isValidCollection(triggerIdList))
      params.put("triggerids", triggerIdList); 
    params.put("selectItems", new String[] { "itemid" });
    String json = this.triggerZabbixApiService.getTriggers(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    try {
      JSONObject result = root.getJSONObject("result");
      return result;
    } catch (Exception e) {
       throw e;
    } 
  }
}
